// 用于操作缓存
import storage from 'good-storage'

import { Song } from 'common/js/classes/song'

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LENGTH = 30

const PLAY_KEY = '__play__'
const PLAY_MAX_LENGTH = 100

const FAVORITE_KEY = '__favorite__'
const FAVORITE_MAX_LENGTH = 100

function insertArray(arr, val, compare, maxLenght) {
    // 处理插入数据以存在于数组中的情况
    const index = arr.findIndex(compare)
    if (index === 0) {
        return
    } else if (index > 0) {
        // 删除旧数据
        arr.splice(index, 1)
    }
    arr.unshift(val)

    if (maxLenght && arr.length > maxLenght) {
        arr.length = maxLenght
    }
}

// 为数组每个元素转化为歌曲对象
function changeToSong(arr) {
    if (!arr) {
        return
    }
    arr = arr.map((item) => {
        return new Song(item)
    })
    return arr
}

export function saveSearchKey(query) {
    let searchs = storage.get(SEARCH_KEY, [])
    const func = (item) => {
        return item === query
    }
    insertArray(searchs, query, func, SEARCH_MAX_LENGTH)

    storage.set(SEARCH_KEY, searchs)

    return searchs
}

export function clearSearch() {
    storage.remove(SEARCH_KEY)
    return []
}

export function loadSearch() {
    return storage.get(SEARCH_KEY, [])
}

export function savePlaySong(song) {
    let songs = storage.get(PLAY_KEY, [])
    const func = (item) => {
        return item.id === song.id
    }
    insertArray(songs, song, func, PLAY_MAX_LENGTH)
    storage.set(PLAY_KEY, songs)
    return songs
}

export function loadPlayHistory() {
    return changeToSong(storage.get(PLAY_KEY, []))
}

export function addFavoriteSong(song) {
    let songs = storage.get(FAVORITE_KEY, [])
    const func = item => {
        return item.id === song.id
    }
    insertArray(songs, song, func, FAVORITE_MAX_LENGTH)
    storage.set(FAVORITE_KEY, songs)
    return songs
}

export function delectFavoriteSong(song) {
    let songs = storage.get(FAVORITE_KEY, [])
    const index = songs.findIndex((item) => {
        return item.id === song.id
    })
    songs.splice(index, 1)
    storage.set(FAVORITE_KEY, songs)
    return songs
}

export function loadFavoriteList() {
    return changeToSong(storage.get(FAVORITE_KEY, []))
}
